package com.example.api.controller;

import com.example.api.common.Result;
import com.example.api.dto.LoginRequestDTO;
import com.example.api.dto.LoginResponseDTO;
import com.example.api.entity.Users;
import com.example.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@CrossOrigin
public class UserController {
    
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<LoginResponseDTO> login(@RequestBody LoginRequestDTO request) {
        try {
            LoginResponseDTO response = userService.loginUser(request.getUsername(), request.getPassword());
            return Result.success(response);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/loginADMIN")
    public Result<LoginResponseDTO> loginADMIN(@RequestBody LoginRequestDTO request) {
        try {
            LoginResponseDTO response = userService.loginAdmin(request.getUsername(), request.getPassword());
            return Result.success(response);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/register")
    public Result<Users> register(@RequestBody Users user) {
        try {
            Users newUser = userService.registerUser(
                user.getUsername(),
                user.getPassword(),
                user.getEmail()
            );
            return Result.success(newUser);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    // 获取全部用户信息
    @GetMapping("/all")
    public List<Users> getAllUsers() {
        return userService.getAllUsers();
    }

    // 模糊搜索用户信息 (通过用户名或邮箱)
    @GetMapping("/search")
    public List<Users> searchUsers(@RequestParam String keyword) {
        return userService.searchUsers(keyword);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable int id) {
        userService.deleteUser(id);
        return "用户删除成功";
    }

    // 修改用户信息
    @PutMapping("/{id}")
    public Users updateUser(@PathVariable int id, @RequestBody Users updatedUser) {
        return userService.updateUser(id, updatedUser);
    }
}
